package org.example.controller;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.example.annotation.CheckPermission;
import org.example.pojo.domain.Artifact;
import org.example.pojo.domain.ArtifactShow;
import org.example.pojo.dto.Artifact.ArtifactBatchBorrowDTO;
import org.example.pojo.dto.Artifact.ReviewDto;
import org.example.result.Result;
import org.example.service.ArtifactService;
import org.example.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/artifacts")
@CrossOrigin
public class ArtifactController {

    @Autowired
    private ArtifactService artifactService;

    /**分页 文物可查看没有被拒绝或者审核中的列表(所有角色)**/
    @CheckPermission({"visitor", "curator", "admin"})
    @GetMapping("/listAvailable")
    public Result listAvailableArtifacts(@RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "10") int size) {
        PageHelper.startPage(page, size);
        List<Artifact> artifacts = artifactService.listAvailableArtifacts();
        return Result.success("文物没有被拒绝或者审核中的分页列表",new PageInfo<>(artifacts));
    }

    /**分页 文物待审核的接口(admin)**/
    @CheckPermission({"admin"})
    @GetMapping("/listPending")
    public Result listPendingArtifacts(@RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "10") int size) {
        PageHelper.startPage(page, size);
        List<Artifact> artifacts = artifactService.listPendingArtifacts();
        return Result.success("文物审核中的分页列表",new PageInfo<>(artifacts));
    }

    /**分页 文物所有状态的列表(curator,admin)**/
    @CheckPermission({"curator", "admin"})
    @GetMapping("/list")
    public Result listArtifacts(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "10") int size) {
        PageInfo<Artifact> pageInfo = artifactService.listArtifacts(page, size);
        return Result.success("分页文物列表", pageInfo);
    }

    /**分页模糊查询 文物可查看没有被拒绝或者审核中的列表(所有角色)**/
    @CheckPermission({"visitor", "curator", "admin"})
    @GetMapping("/like")
    public Result like(@RequestParam String name,@RequestParam Integer page,@RequestParam Integer size) {
        PageHelper.startPage(page, size);
        List<Artifact> artifacts = artifactService.like(name);
        return Result.success("文物模糊查询列表",new PageInfo<>(artifacts));
    }

    /**文物id的详情(所有角色)**/
    @CheckPermission({"visitor", "curator", "admin"})
    @GetMapping("/{id}")
    public Result getArtifact(@PathVariable("id") Integer artifactId) {
        Artifact artifact = artifactService.getArtifactById(artifactId);
        return Result.success("文物id:"+artifactId+"的详细信息",artifact);
    }

    /**添加文物(curator)**/
    @CheckPermission({"curator"})
    @PostMapping("/add")
    public Result addArtifact(@RequestBody Artifact artifact) {
        artifactService.addArtifact(artifact);
        return Result.success("文物添加成功！");
    }

    /**文物更新(curator)**/
    @CheckPermission({"curator"})
    @PutMapping("/update")
    public Result updateArtifact(@RequestBody Artifact artifact) {
        artifactService.updateArtifact(artifact);
        return Result.success("文物更新成功！");
    }

    /**文物id删除(curator)**/
    @CheckPermission({"curator"})
    @DeleteMapping("/delete/{id}")
    public Result deleteArtifact(@PathVariable("id") Integer artifactId) {
        artifactService.deleteArtifact(artifactId);
        return Result.success("文物删除成功！");
    }

    /**上传文物图片(curator,admin)**/
    @CheckPermission({"curator", "admin"})
    @PostMapping("/upload")
    public Result upImg(@RequestParam("file") MultipartFile file) throws IOException {
        String name = "fileName";
        String url = new String();
        try {
            url = UploadUtil.uploadImage(file);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
        return Result.success("上传成功",url);
    }

    /**文物管理人员审核文物的添加(admin)**/
    //
    @CheckPermission({"admin"})
    @PostMapping("/checkArt")
    public Result checkArt(@RequestBody ReviewDto reviewDto) {
        artifactService.reviewArtifact(
                reviewDto.getArtifactId(),
                reviewDto.getReviewStatus()
        );
        return Result.success("审核成功");
    }

    /**处理文物借展(curator)**/
    // 有问题 TODO
    @CheckPermission({"curator"})
    @PostMapping("/borrow")
    public Result borrow(@RequestBody ArtifactShow show) {
        try {
            artifactService.addShow(show);
        }catch (RuntimeException e) {
            return Result.error("请求借出失败: " + e.getMessage());
        }
        return Result.success("借出成功！");
    }

    /**处理借文物(curator)**/
    // 有问题 TODO
    @CheckPermission({"curator"})
    @PostMapping("/batchBorrow")
    public Result batchBorrow(@RequestBody ArtifactBatchBorrowDTO borrowDTO) {
        List<String> errorMessages = new ArrayList<>();

        for (Integer artifactId:borrowDTO.getArtifactId()) {
            ArtifactShow artifactShow = new ArtifactShow();
            artifactShow.setArtifactId(artifactId);
            artifactShow.setExhibitionId(borrowDTO.getExhibitionId());
            artifactShow.setStartTime(borrowDTO.getStarTime());
            artifactShow.setEndTime(borrowDTO.getEndTime());
            try {
                artifactService.addShow(artifactShow);
            }catch (RuntimeException e) {
                errorMessages.add("artifactId " + artifactId + " 失败: " + e.getMessage());
                // continue 会自动进行下一次循环，不需要显式写出
            }
        }

        if (!errorMessages.isEmpty()) {
            return Result.error("部分借出失败: " + String.join("; ", errorMessages));
        }

        return Result.success("全部借出成功");
    }



    /**批准展览请求(curator,admin)**/
    //  TODO 有问题
    // 文物管理员、博物馆管理人员可以批准展览请求
    @CheckPermission({"curator", "admin"})
    @PostMapping("/approveById")
    public Result approveById(@RequestBody ArtifactShow show) {
        try {
            artifactService.approveById(show.getId());
        }catch (RuntimeException e) {
            return Result.error("批准借出失败: " + e.getMessage());
        }
        return Result.success("批准借出成功！");
    }

    @CheckPermission({"curator", "admin"})
    @PostMapping("/batchApproveById")
    public Result batchApproveById(@RequestBody List<Integer> approve) {
        List<String> errorMessages = new ArrayList<>();

        for (Integer showId:approve){
            try {
                artifactService.approveById(showId);
            }catch (RuntimeException e) {
                errorMessages.add("showId " + showId + " 失败: " + e.getMessage());
                // continue 会自动进行下一次循环，不需要显式写出
            }
        }

        if (!errorMessages.isEmpty()) {
            return Result.error("批准借出失败: " + String.join("; ", errorMessages));
        }

        return Result.success("批准借出成功");
    }

    /**查看所有的借出请求(curator,admin)**/
    @CheckPermission({"curator", "admin"})
    @GetMapping("/listBorrow")
    public Result listBorrow(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "10") int size) {
        PageHelper.startPage(page,size);
        List<ArtifactShow> shows = artifactService.listBorrow();
        return Result.success("所有文物",new PageInfo<>(shows));
    }
}

